segment.plot <-function( file="founders3/combined_segments.txt", pdffile="segments.pdf") {
	segs=read.table(file,header=TRUE, as.is=TRUE)
	#if (!is.null(pdffile)) pdf(pdffile)
	par(mfrow=c(2,1))
	par(mar=c(2,4,1,2))
	by (segs, segs$call_name, seg.plot )
	#if (!is.null(pdffile)) dev.off()
}	
	
seg.plot <- function( seg ) {
	#print(seg)
	by( seg, seg$chr, seg.plot.haploid_diploid )
}

seg.plot.haploid_diploid <- function( seg ) {
	#print(seg)
	by( seg, seg$haploid_diploid, seg.plot.chr )
}

seg.plot.chr <- function ( seg ) 
{
	#print(seg)
	
	y=-log10(seg$mismatches_per_SNP)
	yy=seq(2.75, 0, by=-0.25)
	if ( length(yy) > nrow(seg) ) 
	{
		length(yy) = nrow(seg)
	}
	plot( c(0), c(0), xlim=c(0,30), ylim=c(0,3), xlab="Mb", ylab="log error.bp", t="n")


	#
	#	Convert mismatches string to list of numbers
	#
	mismatch_loci=seg$mismatch_loci
	my_f=function(one_string) { return((as.numeric(strsplit(one_string,',')[[1]]))/1.0e6) }
	mismatch_loci=lapply(mismatch_loci,my_f)	

	#
	#	Have y go up and down so we can see the error density without doing a histogram!
	#	Use a band of 0.4/-0.4 around the error rate
	draw_points=function(row_number) 
	{ 
		updown_y = rep(c(seq(-0.4,0.4,0.05), seq(0.4,-0.4,-0.05)) + y[row_number], length(mismatch_loci[[row_number]]))[0:length(mismatch_loci[[row_number]])]
		points(mismatch_loci[[row_number]], updown_y, col='red', cex=0.1) 
	}

	# draw each mismatches for each founder segment
	sapply(1:dim(seg)[1], draw_points)

	# draw greylines at founder segment boundaries	
	abline( v=seg$from.bp/1.0e6, col="grey")
	abline( v=seg$from.bp/1.0e6, col="grey")

	# draw founder segments
	segments( seg$from.bp/1.0e6, y, seg$to.bp/1.0e6, y )

	# label founders
	text( (seg$from.bp/1.0e6 +seg$to.bp/1.0e6)/2, yy, seg$founders)

	# graph
	text( 7, 3, paste(seg$call_name[1], ":", seg$haploid_diploid[1], "chr", seg$chr[1]), col="red")
}

	
	